﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Sustainalytics.ClientDW.Synchronization.SyncESGData.AbstractClassesAndInterfaces;
using Sustainalytics.ClientDW.Synchronization.SyncESGData.RPIndicatorExtendedLogic;
using Sustainalytics.SharedEntities.EsgResearch;
using System.Linq;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.EsgResearchProfileLogic
{
    public class EsgResearchProfileOrchestrator : ICoreEsgSyncOrchestrator<EsgResearchProfile>, IComprehensiveEsgSyncOrchestrator<EsgResearchProfile>
    {
        private readonly EsgResearchProfileCommand esgResearchProfileCommand;
        private readonly RPIndicatorExtendedProcessor rpIndicatorExtendedProcessor;

        public EsgResearchProfileOrchestrator(EsgResearchProfileCommand esgResearchProfileCommand, RPIndicatorExtendedProcessor rpIndicatorExtendedProcessor)
        {
            this.esgResearchProfileCommand = esgResearchProfileCommand;
            this.rpIndicatorExtendedProcessor = rpIndicatorExtendedProcessor;
        }

        async Task ICoreEsgSyncOrchestrator<EsgResearchProfile>.OrchestrateAsync(IList<EsgResearchProfile> coreEsgResearchProfiles, IList<Guid> invalidatedCompaniesIds)
        {
            await OrchestrateAsync(coreEsgResearchProfiles, invalidatedCompaniesIds);
        }

        async Task IComprehensiveEsgSyncOrchestrator<EsgResearchProfile>.OrchestrateAsync(IList<EsgResearchProfile> comprehensiveEsgResearchProfiles, IList<Guid> invalidatedCompaniesIds)
        {
            await OrchestrateAsync(comprehensiveEsgResearchProfiles, invalidatedCompaniesIds);
        }

        private async Task OrchestrateAsync(IList<EsgResearchProfile> esgResearchProfiles, IList<Guid> invalidatedCompaniesIds)
        {
            var indicators = esgResearchProfiles.SelectMany(rp => rp.Indicators).ToList();
            var extraIndicators = esgResearchProfiles
                .Where(rp => rp.ExtraIndicators != null)
                .SelectMany(rp => rp.ExtraIndicators)
                .ToList();

            rpIndicatorExtendedProcessor.AddIndicatorInformation(indicators);
            rpIndicatorExtendedProcessor.AddIndicatorInformation(extraIndicators);

            await esgResearchProfileCommand.ExecuteAsync(esgResearchProfiles, invalidatedCompaniesIds).ConfigureAwait(false);
        }
    }
}
